﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;

class Sparky : AnimatedGameObject
{
    protected float idleTime;
    protected float yoffset;
    protected float initialY;
    protected bool dead;

    public Sparky(float initialY)
    {
        this.LoadAnimation("Sprites/Sparky/spr_electrocute@6x5", "electrocute", false);
        this.LoadAnimation("Sprites/Sparky/spr_idle", "default", true);
        this.LoadAnimation("Sprites/Player/spr_explode@5x5", "explode", false, 0.04f);
        this.PlayAnimation("default");
        this.initialY = initialY;
        Reset();
    }

    public override void Reset()
    {
        idleTime = (float)GameEnvironment.Random.NextDouble() * 5;
        this.position.Y = initialY;
        yoffset = 120;
        velocity = Vector2.Zero;
        dead = false;
    }

    public override void Update(GameTime gameTime)
    {
        base.Update(gameTime);
        if (!dead)
        {
            if (idleTime <= 0)
            {
                this.PlayAnimation("electrocute");
                if (this.velocity.Y != 0)
                {
                    // falling down
                    yoffset -= this.velocity.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
                    if (yoffset <= 0)
                        this.velocity.Y = 0;
                    else if (yoffset >= 120.0f)
                        this.Reset();
                }
                else if (Current.AnimationEnded)
                    this.velocity.Y = -60;
            }
            else
            {
                this.PlayAnimation("default");
                idleTime -= (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (idleTime <= 0.0f)
                    this.velocity.Y = 300;

            }
            CheckPlayerCollision();
            CheckBombCollision();
        }
    }

    public void CheckPlayerCollision()
    {
        if (!dead)
        {
            Player player = GameWorld.Find("player") as Player;
            if (this.CollidesWith(player) && idleTime <= 0.0f)
                player.Die(false);
        }
    }

    public void CheckBombCollision()
    {
        if (GameWorld.Find("bomb") == null)
            return;
        Bomb bomb = GameWorld.Find("bomb") as Bomb;
        if (this.CollidesWith(bomb) && this.Visible)
            Kill();
    }

    public void Kill()
    {
        dead = true;
        PlayAnimation("explode");
        GameEnvironment.AssetManager.PlaySound("Sounds/snd_explode");
    }
}
